import axios from "axios";
import cookie from "vue-cookies";
import router from "./router";
import { Toast } from "vant";
axios.create({
  // 这里是配置项
  timeout: 7000
});
// axios.defaults.withCredentials = true;
axios.defaults.baseURL = process.env.VUE_APP_BACKURL + "/";
// 拦截请求
axios.interceptors.request.use(
  config => {
    console.log(cookie.get("token"));
    let token = cookie.get("token");
    // token = `0258da6e-4738-4875-8068-9bfb7b31441b`
    if (token) {
      config.headers.Authorization = token;
    } else {
      router.replace({
        path: "/"
      });
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// 拦截响应
axios.interceptors.response.use(
  response => {
    if (!response.data.code) {
      Toast.fail(response.data.msg);
      Promise.reject(response.data);
    } else {
      return response.data;
    }
  },
  err => {
    console.log(err.response);
    if (err.response) {
      switch (err.response.status) {
        case 401:
          Toast.fail(err.response.data.msg);
          cookie.remove("token");
          // 这里写清除token的代码
          router.replace({
            path: "/"
          });
      }
    }
    return Promise.reject(err);
  }
);
